package codetop.microsoft.T22;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 18362
 * @Create: 2022-08-13 18:06:59 星期六
 */
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        dfs(res, sb, n, 0, 0);
        return res;
    }

    private void dfs(List<String> res, StringBuilder sb, int n, int left, int right) {
        if (right == n) {
            res.add(sb.toString());
            return;
        }
        if (left < n) {
            sb.append('(');
            dfs(res, sb, n, left+1, right);
            sb.deleteCharAt(sb.length()-1);
        }
        if (right < left) {
            sb.append(')');
            dfs(res, sb, n, left, right+1);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}
